package com.travel.server.manager.impl.dal;

import com.travel.common.CommonConstant;
import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CollectionUtil;
import com.travel.server.manager.dao.AdvertisingPositionInfoDao;
import com.travel.server.manager.model.AdvertisingPositionInfo;
import com.travel.server.manager.model.AdvertisingPositionInfoExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: LiZhenhui
 * @Date: 2018/12/20 14:49
 * @Desc:
 */
@Component
@Slf4j
public class PositionDal {

    @Autowired
    private AdvertisingPositionInfoDao dao;

    public PageDto<AdvertisingPositionInfo> selectByPage(Integer offset, Integer limit){
        AdvertisingPositionInfoExample example = new AdvertisingPositionInfoExample();
        AdvertisingPositionInfoExample.Criteria criteria = example.or();
        criteria.andStateEqualTo(CommonConstant.YES);
        Integer total = dao.countByExample(example);
        example.setOffset(offset);
        example.setLimit(limit);
        example.setOrderByClause("update_time desc");
        List<AdvertisingPositionInfo> list = dao.selectByExample(example);
        return new PageDto<>(list, total);
    }

    public AdvertisingPositionInfo selectById(Integer id){
        AdvertisingPositionInfo info = dao.selectByPrimaryKey(id);
        if(info == null){
            log.info("未查询到广告版位信息 id {}", id);
            throw new WorkException(WorkCode.RECORD_NOT_EXIST);
        }
        return info;
    }

    public void insertOrUpdate(AdvertisingPositionInfo advertisingPositionInfo){
        if(advertisingPositionInfo.getId() == null){
            dao.insertSelective(advertisingPositionInfo);
        }else{
            dao.updateByPrimaryKey(advertisingPositionInfo);
        }
    }

    public Map<Integer, String> makeMap(List<Integer> positionList){
        AdvertisingPositionInfoExample example = new AdvertisingPositionInfoExample();
        AdvertisingPositionInfoExample.Criteria criteria = example.or();
        criteria.andStateEqualTo(CommonConstant.YES);
        criteria.andIdIn(positionList);
        List<AdvertisingPositionInfo> list = dao.selectByExample(example);
        Map<Integer, String> map = new HashMap<>();
        if(!CollectionUtil.isEmpty(list)){
            for(AdvertisingPositionInfo info : list){
                map.put(info.getId(), info.getPositionName());
            }
        }
        return map;
    }
}
